package com.maotai.app.thread;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;

import com.maotai.app.bean.MaotaiAppCookie;
import com.maotai.app.bean.MaotaiAppString;
import com.maotai.app.service.MaotaiAppService;
import com.maotai.app.util.MaotaiAppHttpClientUtil;
import com.maotai.llzhou.util.IPFactory;

public class MaoTaiAppLoginThread extends Thread {
	private MaotaiAppService maotaiAppService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;
	
	public MaoTaiAppLoginThread(MaotaiAppService maotaiAppService,
			Map<String, Object> zhanghao, String ipAndPort) {
		this.maotaiAppService = maotaiAppService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
	}

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	public MaotaiAppService getMaotaiAppService() {
		return maotaiAppService;
	}

	public void setMaotaiAppService(MaotaiAppService maotaiAppService) {
		this.maotaiAppService = maotaiAppService;
	}

	@Override
	public void run() {
		try {
			MaotaiAppHttpClientUtil hcu = MaotaiAppHttpClientUtil.getInstance();
			// 先登录
			
			MaotaiAppCookie mc = new MaotaiAppCookie();
			Map<String, String> maps = new HashMap<String, String>();
			//userCode=nickboowen&userPassword=MTk4NjA2MTg&loginType=name&loginSource=2&loginFlag=1
			maps.put("userCode", zhanghao.get("code")+"");
			maps.put("userPassword", zhanghao.get("pwd")+"");
			maps.put("loginType", "name");
			maps.put("loginSource", "2");
			//loginSource=2&loginType=name&userCode=13372007847&userPassword=cTE5ODYwNjE4 手机端
			RequestConfig requestConfig = IPFactory.getKdRequestConfig(ipAndPort);
			try {
				mc = hcu.sendHttpPostProxy(MaotaiAppString.LOGIN_URL_NEW,
						mc, maps, requestConfig,null);
			} catch (Exception e) {
				e.printStackTrace();
				zhanghao.put("loginstatus", "0");
				maotaiAppService.updateMaotaiAppLoginStatus(zhanghao);
				return;
			}
			String auth = mc.getAuth();
			System.out.println(zhanghao.get("code") + "----" + auth);
			
			// 得到登录之后的标志
			if (mc.getAuth() != null && !"".equals(mc.getAuth())) {
				zhanghao.put("auth",auth);
				maotaiAppService.updateAppAuth(zhanghao);
			}else{
				zhanghao.put("loginstatus", "0");
				maotaiAppService.updateMaotaiAppLoginStatus(zhanghao);
			}
		} catch (Exception e) {
			e.printStackTrace();
			zhanghao.put("loginstatus", "0");
			try {
				maotaiAppService.updateMaotaiAppLoginStatus(zhanghao);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
	}
}
